package com.shujia.flink.kafka

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import java.util.Properties

object DEmo4KafkaTran {
  def main(args: Array[String]): Unit = {

    val properties = new Properties()

    //指定kafka broker地址
    properties.setProperty("bootstrap.servers", "master:9092,node2:9092,node2:9092")

    //设置key 和value的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    //设置事务id
    properties.setProperty("transactional.id", "asdas")

    val producer = new KafkaProducer[String, String](properties)


    /**
     *
     * 开启事务
     */
    //初始化事务
    producer.initTransactions()
    //开启事务
    producer.beginTransaction()

    //数据实际上已经发生到kafka，只是一个未提交的状态
    producer.send(new ProducerRecord[String, String]("tran", "java"))

    Thread.sleep(2000)

    producer.send(new ProducerRecord[String, String]("tran", "java"))

    Thread.sleep(2000)
    producer.send(new ProducerRecord[String, String]("tran", "java"))

    //提交事务
    producer.commitTransaction()

    //如果出现异常，回滚事务
    //producer.abortTransaction()

    /**
     *
     * --isolation-level read_committed : 读已提交，默认可以读取到未提交的数据
     * kafka-console-consumer.sh --bootstrap-server master:9092,node1:9092,node2:9092 --isolation-level read_committed --from-beginning --topic tran
     *
     */

  }

}
